//
//  PeiSongViewController.m
//  LazyCat
//
//  Created by linhui on 15/12/12.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "PeiSongViewController.h"
#import "ShopManagerCell.h"
#import "AFNetworkHandler.h"
@interface PeiSongViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    UIButton *_doneBtn;
    NSString *peisongPay;
    NSString *minPay;
}
@end

@implementation PeiSongViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
}
- (void)createUI {
    self.view.backgroundColor = BackColor;
    self.automaticallyAdjustsScrollViewInsets=NO;
    [self initNav:self.titleStr doBack:YES];
    _dataArray = [NSMutableArray arrayWithObjects:@"请输入起送金额",@"请输入配送费", nil];
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64) style:UITableViewStyleGrouped];
    _tableView.dataSource=self;
    _tableView.delegate=self;
    _tableView.scrollEnabled = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [_tableView addGestureRecognizer:tap];
    _doneBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _doneBtn.frame = CGRectMake(10, 180, ScreenWidth - 20, 40);
    [_doneBtn setTitle:@"保存" forState:UIControlStateNormal];
    [_doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _doneBtn.backgroundColor = MainColor;
    [_doneBtn addTarget:self action:@selector(doneBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    _doneBtn.layer.cornerRadius = 5;
    _doneBtn.clipsToBounds = YES;
    [self.view addSubview:_doneBtn];
}

#pragma mark - 保存按钮
- (void)doneBtnClick {
    
    [self.view endEditing:YES];
    
//    NSString *url = [NSString stringWithFormat:upPayMoneyUrl,[AppData share].username,minPay,peisongPay];
    NSString *url = [NSString stringWithFormat:UpdateServerAmountUrl,[AppData share].username,[AppData share].username,minPay,peisongPay];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dic = result;
        if ([dic[@"r"] isEqualToString:@"T"]) {
            [[MessShowView share] showWithMess:@"修改成功" login:YES];
            [AppData share].serveramount = peisongPay; // 配送费
            [AppData share].minSentamount = minPay; // 起送金额
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            [[MessShowView share] showWithMess:dic[@"m"]];
        }
    }];
}
-(void)tapAction {
    [self.view endEditing:YES];
}
#pragma mark -- tableView代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ShopManagerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"managercell"];
    if(cell==nil){
        cell = [[NSBundle mainBundle]loadNibNamed:@"ShopManagerCell" owner:nil options:nil][0];
    }
    if (indexPath.row == 0) {
        cell.leftLabel.text = @"起送金额";
        
        if ([AppData share].minSentamount.length > 0) {
            cell.rightTextField.text = [AppData share].minSentamount;
            minPay = [AppData share].minSentamount ;
        }
    }else if (indexPath.row == 1){
        cell.leftLabel.text = @"配送费";
        if ([AppData share].serveramount.length > 0) {
            cell.rightTextField.text = [AppData share].serveramount;
            peisongPay = [AppData share].serveramount;
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.rightTextField.placeholder = _dataArray[indexPath.row];
     cell.rightTextField.tag = 100 + indexPath.row;
    cell.rightTextField.delegate = self;
    cell.rightTextField.keyboardType = UIKeyboardTypeDecimalPad;
    cell.rightTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    return cell;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    [textField resignFirstResponder];
    if (textField.tag == 100) {
        minPay = textField.text;
    }else{
        peisongPay = textField.text;
    }
    return YES;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //if (textField == _textField1) {
    NSScanner      *scanner    = [NSScanner scannerWithString:string];
    NSCharacterSet *numbers;
    NSRange         pointRange = [textField.text rangeOfString:@"."];
    
    if ( (pointRange.length > 0) && (pointRange.location < range.location  || pointRange.location > range.location + range.length) )
    {
        numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    }
    else
    {
            numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
    }
    
    if ( [textField.text isEqualToString:@""] && [string isEqualToString:@"."] )
    {
        return NO;
    }
    
    short remain = 2; //默认保留2位小数
    
    NSString *tempStr = [textField.text stringByAppendingString:string];
    NSUInteger strlen = [tempStr length];
    if(pointRange.length > 0 && pointRange.location > 0){ //判断输入框内是否含有“.”。
        if([string isEqualToString:@"."]){ //当输入框内已经含有“.”时，如果再输入“.”则被视为无效。
            return NO;
        }
        if(strlen > 0 && (strlen - pointRange.location) > remain+1){ //当输入框内已经含有“.”，当字符串长度减去小数点前面的字符串长度大于需要要保留的小数点位数，则视当次输入无效。
            return NO;
        }
    }
    NSRange zeroRange = [textField.text rangeOfString:@"0"];
    if(zeroRange.length == 1 && zeroRange.location == 0){ //判断输入框第一个字符是否为“0”
        if(![string isEqualToString:@"0"] && ![string isEqualToString:@"."] && [textField.text length] == 1){ //当输入框只有一个字符并且字符为“0”时，再输入不为“0”或者“.”的字符时，则将此输入替换输入框的这唯一字符。
            textField.text = string;
            return NO;
        }else{
            if(pointRange.length == 0 && pointRange.location > 0){ //当输入框第一个字符为“0”时，并且没有“.”字符时，如果当此输入的字符为“0”，则视当此输入无效。
                if([string isEqualToString:@"0"]){
                    return NO;
                }
            }
        }
    }
    NSString *buffer;
    if ( ![scanner scanCharactersFromSet:numbers intoString:&buffer] && ([string length] != 0) )
    {
        return NO;
    }
    //}
    return YES;
}
@end
